<?php
	$conn = mysql_connect("localhost", "root", "");
	$db = mysql_select_db( 'vandes4_PROJECT',   $conn);

	$keyword = $_GET['keyword'];
	if($keyword == "")
	{
		exit();
	}
	echo "<h2>Results for \"".$keyword."\"</h2>";
	
	$sql = "select word, crawl_id from keyword where word LIKE '%".$keyword."%'";
	$result = mysql_query($sql) or die(mysql_error());
	
	//ids is an array mapping url id to full path url.
	$ids = array();
	
	//results is an associative array mapping url id to keyword count
	$results = array();
	
	//not currently using edit distances, may want to use it in weighting pages.
	//editdistances is an associative array mapping a url id to the count of edit 
		//distances between the query and the keywords that matched it
	$editDistances = array();
	
	
	while($row = mysql_fetch_assoc($result))
	{
		$id = $row['crawl_id'];
		$word = $row['word'];
		
		//if we haven't run across this page as a result yet, record its id
		if(!isset($ids[$id]))
		{
			$sql = "select full_path from crawl where crawl_id = ".$id." limit 1";
			$fullpath = mysql_query($sql) or die(mysql_error());
			$row = mysql_fetch_assoc($fullpath);
			$url = $row['full_path'];
			$ids[$id] = $url;
		}
		
		//if we haven't seen this page yet, create an entry for it in results.
		if(!isset($results[$id]))
		{
			$results[$id] = 0;
		}
		
		//increment the count of times this keyword has matched this url
		$results[$id]++;
		
		//maybe we will use edit distances somewhere too?
		if(!isset($editDistances[$id]))
		{
			$editDistances[$id] = 0;
		}
		$editDistances[$id] += abs(strlen($word) - strlen($keyword));
	}
	
	//sort the results in descending order.
	arsort($results);
	
	//display them.
	foreach($results as $id=>$count)
	{
		echo "<a href = \"".$ids[$id]."\">".$ids[$id]."</a>, with count $count<br>";
	}
	
	
?>